package open.tech.dawn.redis.service;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import open.tech.dawn.core.service.ICacheService;
import org.springframework.cache.Cache;
import org.springframework.cache.support.AbstractCacheManager;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;

@Service
public class CacheServiceImpl implements ICacheService {

    @Resource
    private RedisCacheManager cacheManager;


    public RedisCache createRedisCache(String cacheName, int expirationSeconds) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(expirationSeconds))//设置缓存过期时间
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        RedisCache createRedisCache = (RedisCache) ReflectUtil.invoke(cacheManager, ClassUtil.getDeclaredMethod(RedisCacheManager.class, "createRedisCache", String.class, RedisCacheConfiguration.class), cacheName, config);
        ReflectUtil.invoke(cacheManager, ClassUtil.getDeclaredMethod(AbstractCacheManager.class, "addCache", Cache.class), createRedisCache);
        return createRedisCache;
    }


    @Override
    public void put(String cacheName, String key, Object value, int expirationSeconds) {
        createRedisCache(cacheName, expirationSeconds).put(key, value);
    }

    @Override
    public void put(String cacheName, String key, Object value) {
        cacheManager.getCache(cacheName).put(key, value);
    }

    @Override
    public Object get(String cacheName, String key) {
        return cacheManager.getCache(cacheName).get(key);
    }

    @Override
    public void remove(String cacheName) {
        cacheManager.getCache(cacheName).clear();
    }
}
